import React, { useRef, useState, useImperativeHandle } from 'react';
import { useClickAway } from 'react-use';
import { Employee } from '@/pages/Organization/OrgFlow/components';

const CARD_WIDTH = 300;
const CARD_HEIGHT = 274;

/**
 * 员工列表的 Tooltips 组件
 * @param props
 * @returns {JSX.Element}
 * @constructor
 */
const EmployeeTooltip = React.forwardRef((props, ref) => {
    const [rect, setRect] = useState();
    const [employeeInfo, setEmployeeInfo] = useState();
    const { left, top, width } = rect || {};
    const [visible, setVisible] = useState(false);
    const wrapperClassName = 'ant-popover employeePopover ant-popover-placement-top';
    const wrapperStyle = {
        position: 'fixed',
        left: left - CARD_WIDTH / 2 + width / 2 || 0,
        top: top - CARD_HEIGHT || 0
    };

    const tooltipRef = useRef();
    // 点击区域以外的位置关门弹出层
    useClickAway(tooltipRef, () => {
        if (visible) {
            setVisible(false);
        }
    });

    useImperativeHandle(ref, () => ({
        show: (_employeeInfo, _rect) => {
            setTimeout(() => {
                setEmployeeInfo(_employeeInfo);
                setRect(_rect);
                setVisible(true);
            }, 50);
        }
    }));

    // render
    return (
        visible && (
            <div ref={tooltipRef} className={wrapperClassName} style={wrapperStyle}>
                <div className="ant-popover-content">
                    <div className="ant-popover-arrow" />
                    <div className="ant-popover-inner" role="tooltip">
                        <div>
                            <div className="ant-popover-inner-content">
                                {employeeInfo && (
                                    <Employee
                                        employeeCode={employeeInfo.employeeCode}
                                        organizationCode={employeeInfo.organizationCode}
                                        organizationType={employeeInfo.organizationType}
                                        noSubordinates
                                    />
                                )}
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        )
    );
});

export default EmployeeTooltip;
